import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import { Bk_Student_Info } from './bk_student_info.entity';
import * as fs from 'fs';
import { join } from 'path';
import { v1 } from 'node-uuid';
@Injectable()
export class StudentInfoService {
    constructor(
        @InjectRepository(Bk_Student_Info)
        private readonly studentInfoRepository: Repository<Bk_Student_Info>
    ) { }

    async add(files: any, student: any): Promise<Bk_Student_Info> {
        const file_path = student.name + ' ' + student.idCard  + ' ' + student.phone + ' ' + student.email;
        if (!fs.existsSync(join(__dirname, '..', 'public', 'students', file_path))) {
            fs.mkdirSync(join(__dirname, '..', 'public', 'students', file_path));
        }
        const idCardPhoto_path = v1() + '.' + files.idCardPhoto[0].originalname.split('.')[1];
        const bluePhoto_path = v1() + '.' + files.bluePhoto[0].originalname.split('.')[1];
        fs.writeFileSync(join(__dirname, '..', 'public', 'students', file_path, idCardPhoto_path), files.idCardPhoto[0].buffer);
        fs.writeFileSync(join(__dirname, '..', 'public', 'students', file_path, bluePhoto_path), files.bluePhoto[0].buffer);
        student.idCardPhoto_path = idCardPhoto_path;
        student.bluePhoto_path = bluePhoto_path;
        return await this.studentInfoRepository.save(student);
    }
    async delete(id: number): Promise<DeleteResult> {
        return await this.studentInfoRepository.delete(id);
    }
    async update(id: number, student: any): Promise<UpdateResult> {
        return await this.studentInfoRepository.update(id, student);
    }

    async findAll(): Promise<Bk_Student_Info[]> {
        return await this.studentInfoRepository.find({ order: { id: "ASC" } });
    }

    async getStudentInfoByIdCard(query: any): Promise<Bk_Student_Info> {
        return await this.studentInfoRepository.findOne({ where: { idCard: query.idCard } });
    }

}
